<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">
        当前位置：首页
      </el-breadcrumb-item>
      <el-breadcrumb-item>服务卡管理</el-breadcrumb-item>
      <el-breadcrumb-item>服务卡查询</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索区 -->
      <el-form
        ref="searchFormRef"
        :inline="true"
        :model="queryInfo.query"
        size="mini"
      >
        <el-form-item label="产品名称" prop="product_id">
          <el-select
            v-model="queryInfo.query.product_id"
            placeholder="请选择"
            filterable
            clearable
          >
            <el-option
              v-for="item in selectData.product"
              :key="item.id"
              :label="item.name + '【' + item.id + '】'"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="卡类型" prop="card_type">
          <el-select
            v-model="queryInfo.query.card_type"
            placeholder="请选择"
            filterable
            clearable
          >
            <el-option key="0" label="单次卡" value="0"> </el-option>
            <el-option key="1" label="套卡" value="1"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryInfo.query.status"
            placeholder="请选择"
            filterable
            clearable
          >
            <el-option key="0" label="未使用" value="0"> </el-option>
            <el-option key="1" label="使用中" value="1"> </el-option>
            <el-option key="2" label="已使用" value="2"> </el-option>
            <el-option key="3" label="已过期" value="3"> </el-option>
            <el-option key="4" label="已删除" value="4"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关键字" prop="keyword">
          <el-input
            v-model="queryInfo.query.keyword"
            placeholder="请输入卡号或手机号"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            class="theme-background-color"
            size="mini"
            @click="searchList"
          >
            搜索
          </el-button>
          <el-button size="mini" @click="resetSearchForm"> 重置 </el-button>
        </el-form-item>
      </el-form>
      <!-- 操作区域 -->
      <div>
        <el-button
          icon="el-icon-download"
          size="mini"
          :loading="btnLoading"
          @click="downloadExcel"
        >
          导出数据
        </el-button>
      </div>
      <!-- 用户列表区域 -->
      <el-table :data="list" border stripe>
        <!-- <el-table-column label="序号" type="index"></el-table-column> -->
        <el-table-column
          label="卡号"
          prop="code"
          min-width="120px"
        ></el-table-column>
        <el-table-column
          label="手机号"
          prop="mobile"
          min-width="100px"
        ></el-table-column>
        <el-table-column label="卡类型" prop="card_type"></el-table-column>
        <el-table-column
          label="卡名称【ID】"
          min-width="150px"
          max-width="300px"
        >
          <template slot-scope="scope">
            {{ scope.row.service_card_name }}【{{ scope.row.id }}】
          </template>
        </el-table-column>
        <el-table-column label="服务次数" prop="can_use_num"></el-table-column>
        <el-table-column
          label="已使用次数"
          prop="used_num"
          min-width="90px"
        ></el-table-column>
        <el-table-column
          label="使用城市"
          prop="area_limit_name"
          min-width="150px"
          max-width="300px"
        ></el-table-column>
        <el-table-column label="状态" prop="status.name"></el-table-column>
        <el-table-column label="是否使用" prop="flag"></el-table-column>
        <el-table-column label="所属产品" min-width="150px" max-width="300px">
          <template slot-scope="scope">
            {{ scope.row.product_name }}【{{ scope.row.product_id }}】
          </template>
        </el-table-column>
        <el-table-column label="有效期" min-width="180px">
          <template slot-scope="scope">
            {{ scope.row.start_date }} ~ {{ scope.row.end_date }}
          </template>
        </el-table-column>
        <el-table-column
          label="发放时间"
          prop="create_time"
          min-width="90px"
        ></el-table-column>
        <el-table-column label="操作" width="100px" fixed="right">
          <template slot-scope="scope">
            <el-link
              type="primary"
              v-if="scope.row.status.id != 4"
              @click="delayDialogVisibles(scope.row)"
            >
              延期
            </el-link>
            &nbsp;
            <el-link
              type="danger"
              v-if="scope.row.status.id != 4"
              @click="deleteServiceCard(scope.row.id)"
            >
              删除
            </el-link>
            &nbsp;
            <el-link
              type="primary"
              v-if="
                scope.row.status.id == 1 ||
                scope.row.status.id == 2 ||
                scope.row.status.id == 3
              "
              @click="changeTab(scope.row.id)"
            >
              使用明细
            </el-link>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 延期操作对话框 -->
    <el-dialog
      title="延期"
      :visible.sync="delayDialogVisible"
      width="30%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <!-- 弹框内容 -->
      <el-form style="margin: 10px" :model="deferDateForm">
        <el-form-item label="生效日期" prop="start_date">
          <el-date-picker
            v-model="deferDateForm.start_date"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="失效日期" prop="end_date">
          <el-date-picker
            v-model="deferDateForm.end_date"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button class="theme-background-color" @click="deferCoupon()">
          保存
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      queryInfo: {
        query: {
          product_id: '',
          card_type: '',
          status: '',
          keyword: '',
          record_id: ''
        },
        pagenum: 1,
        pagesize: 20
      },
      selectData: [],
      list: [],
      total: 0,
      btnLoading: false,

      // 延期操作对话框的显示与隐藏
      delayDialogVisible: false,
      deferDateForm: {
        id: '',
        start_date: '',
        end_date: ''
      }
    }
  },
  created() {
    if (this.queryInfo.query) {
      // 从路由上获取参数
      this.queryInfo.query.record_id = this.$route.query.record_id
      this.queryInfo.query.keyword = this.$route.query.keyword
    }
    this.getSelectData()
    this.getListData()
  },
  methods: {
    async getSelectData() {
      const { data: res } = await this.$http.post('/admin/data/find', {
        code: 'product'
      })
      // 返回结果
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.selectData = res.data
    },
    searchList() {
      this.queryInfo.pagenum = 1
      this.getListData()
    },
    resetSearchForm() {
      //   console.log(this)
      this.queryInfo.query = Object.assign(this.$options.data().queryInfo.query) //重置表单
      this.$refs.searchFormRef.resetFields()
      // console.log(this.queryInfo.query)
      this.getListData()
    },
    async getListData() {
      // 返回数据重命名为res
      const { data: res } = await this.$http.post(
        '/admin/service_card/list',
        this.queryInfo
      )
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.list = res.data.list
      this.total = res.data.total
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      //   console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getListData()
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      //   console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getListData()
    },
    async deleteServiceCard(id) {
      // 弹框询问是否删除
      const confirmResult = await this.$confirm('确定删除该服务卡？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消操作')
      }
      const { data: res } = await this.$http.post(
        '/admin/service_card/remove',
        {
          id: id
        }
      )
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getListData()
    },
    // 打开延期服务卡的弹窗并赋予初始值
    async delayDialogVisibles(row) {
      this.delayDialogVisible = true
      this.deferDateForm.id = row.id
      this.deferDateForm.start_date = row.start_date
      this.deferDateForm.end_date = row.end_date
    },
    async deferCoupon() {
      const confirmResult = await this.$confirm(
        '是否确认延期服务卡【' + this.deferDateForm.id + '】',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消延期')
      }
      const { data: res } = await this.$http.post(
        '/admin/service_card/delay',
        this.deferDateForm
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.delayDialogVisible = false
      this.getListData()
    },
    async downloadExcel() {
      this.btnLoading = true
      this.$http({
        method: 'post',
        url: '/admin/service_card/export',
        data: this.queryInfo.query,
        headers: {
          token: window.sessionStorage.getItem('token')
        },
        responseType: 'blob'
      })
        .then((res) => {
          this.btnLoading = false
          if (res.data.type) {
            // 文件下载
            const blob = new Blob([res.data], {
              type: 'application/vnd.ms-excel'
            })
            let link = document.createElement('a')
            link.href = URL.createObjectURL(blob)
            link.setAttribute('download', '服务卡数据.xlsx')
            link.click()
            link = null
            this.$message.success('导出成功')
          } else {
            // 返回json
            this.$message.warning(res.data.msg)
          }
        })
        .catch((err) => {
          this.btnLoading = false
          this.$message.error(err)
        })
    },
    changeTab(id) {
      const path = '/order/PetHousekeeping'
      this.$router.push({ path: path, query: { record_id: id } })
      this.$emit('updateActivePath', path)
      window.sessionStorage.setItem('activePath', path)
    }
  }
}
</script>

<style lang="less" scoped>
</style>
